﻿import Vue from 'vue'
import Router from 'vue-router'

import Home from '@/views/Home'
import CreateTicket from '@/views/CreateTicket'
import alreadyProcess from '@/views/alreadyProcess/alreadyProcess'
import waitProcess from '@/views/waitProcess/waitProcess'
import myInitiation from '@/views/myInitiation/myInitiation'
import copyMe from '@/views/copyMe/copyMe'
import TicketDetails from '@/views/TicketDetails/TicketDetails'
import comment from '@/views/comment/comment'
import handleTicket from '@/views/handleTicket/handleTicket'
import deliverTicket from '@/views/deliverTicket/deliverTicket'
import printTicket from '@/views/printTicket/printTicket'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      beforeEnter(to,from,next){
        if(from.name == "waitProcess" || from.name == "myInitiation" || from.name == "copyMe" || from.name == 'alreadyProcess'){
          store.state.is_cache = true
        }
        next()
      }
    },
    {
      path: '/CreateTicket',
      name: 'CreateTicket',
      component: CreateTicket,
      meta:{
        keepAlive:false,
      }
    },
    {
      path: '/waitProcess',
      name: 'waitProcess',
      component: waitProcess,
      meta:{
        keepAlive:true,
      }
    },
    {
      path: '/alreadyProcess',
      name: 'alreadyProcess',
      component: alreadyProcess,
      meta:{
        keepAlive:true,
      }
    },
    {
      path: '/myInitiation',
      name: 'myInitiation',
      component: myInitiation,
      meta:{
        keepAlive:true,
      }
    },
    {
      path: '/copyMe',
      name: 'copyMe',
      component: copyMe,
      meta:{
        keepAlive:true,
      }
    },
    {
      path: '/TicketDetails',
      name: 'TicketDetails',
      component: TicketDetails,
      meta:{
        keepAlive:false,
      }
    },
    {
      path: '/comment',
      name: 'comment',
      component: comment,
      meta:{
        keepAlive:false,
      }
    },
    {
      path: '/handleTicket',
      name: 'handleTicket',
      component: handleTicket,
      meta:{
        keepAlive:false,
      }
    },
    {
      path: '/deliverTicket',
      name: 'deliverTicket',
      component: deliverTicket,
      meta:{
        keepAlive:false,
      }
    },
    {
      path: '/printTicket',
      name: 'printTicket',
      component: printTicket,
      meta:{
        keepAlive:false,
      }
    },
  ]
})
import axios from 'axios'
import qs from 'qs'
import store from '../store/store.js'
import utils from '../utils/utils'
import * as dd from 'dingtalk-jsapi';
// 钉钉鉴权
function requestAuthCode () {
  return new Promise((resolve, reject)=>{
    dd.ready(()=>{
      dd.runtime.permission.requestAuthCode({
        corpId: store.getters.corpId, // 企业id
        onSuccess: function (info) {
          let code = info.code // 通过该免登授权码可以获取用户身份
          resolve(code)
        },
        onFail : function(err) {
          reject(JSON.stringify(err))
        }
      })
    })
  })
}
// 获取用户信息
function getUser(next) {
  axios.get('api/v1/account/users/iam/').then(res => {
    if (res.status == 200) {
      utils.setCache('user', res.data)
      next()
    }
  }).catch(err => {
    console.log(err.response)
  })
}
// 登录保存token
function login(next) {
  requestAuthCode().then(code => {
     let data = {
       code: code
     }
     axios.post('/dd_login/', qs.stringify(data)).then( res => {
       if(res.data.token){
         utils.setCookie('token',res.data.token, 1);
         utils.setCache('user',res.data.user);
         axios.defaults.headers['Authorization'] = 'JWT ' + res.data.token;
         JsapiTicket(next)
       }
     }).catch(err => {
       console.log(err.response)
     })
 })
}

// JSapi鉴权
function JsapiTicket(next){
  axios.get('/api/get_js_api/').then((res)=>{
    if(res.data){
      dd.config({
        agentId: res.data.agentId,
        corpId: res.data.corpId,
        timeStamp:res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        signature: res.data.signature,
        jsApiList: [
          'biz.util.open',
          'biz.ding.create',
        ]
      });
      getUser(next)
    }else{
      dd.device.notification.alert({
        message: "鉴权失败,请重新进入应用",
        buttonName: "确定",
      })
    }
  }).catch((err)=>{
    console.log(err)
  })
}

// 守卫
if (process.env.NODE_ENV === 'development') {
  router.beforeEach((to, from, next) => {
    store.dispatch('login', {username: "admin",password: "1qaz!QAZ"}).then(res=>{
      getUser(next)
    })
  })
} else if (process.env.NODE_ENV === 'production') {
  router.beforeEach((to, from, next) => {
    if (utils.getCookie('token')) {
      axios.defaults.headers['Authorization'] = 'JWT ' + utils.getCookie('token');
      if(!utils.getCookie('user')){
        getUser(next)
      }else{
        next()
      }
    } else {
      login(next)
    }
  })
}

export default router


